<template>
    <view class="page bg-fff">
        <view class="tabsWrap">
            <u-tabs keyName="label" :list="tabsLabel" :current="current" lineColor="#007235" @change="changeTabs" active-color="#007235"></u-tabs>
        </view>
        
        <view class="mapWrap">
            <map class="map u-skeleton-fillet" id="plateMap" :latitude="latitude" :longitude="longitude" :polygons="platePolygons" :markers="markers" @callouttap="clickMarker" @tap="clickMap" @regionchange="mapMoveChange" v-if="latitude"></map>
            
            <cover-view class="topBtnGroup flex">
                <cover-view class="openAreaBtn flex bg-fff" @click="changeSelect" v-if="plateSelect.length > 0">
                    <cover-view class="right-5">{{ plateSelect[currPlate].title }}</cover-view>
                    <cover-view class="iconArrow bg-theme">
                        <cover-image class="iconImg" :class="showPlate?'upArrow':''" src="https://image.srea.org.cn/xcx/icon/icon-arrow-down-fff.png"></cover-image>
                    </cover-view>
                </cover-view>
                
                <cover-view class="col-fff font10 flex">
                    <block v-for="(tag, tagI) in tags" :key="tagI">
                        <cover-view class="tag left-10" :style="{backgroundColor: tag.color}">{{ tag.label }}</cover-view>
                    </block>
                </cover-view>
            </cover-view>
            
            <cover-view class="selecWrap font13 text-center bg-fff" v-if="showPlate">
                <cover-view class="selectBtn" v-for="(item, index) in plateSelect" :key="index" @click="changePlate(index)">{{ item.title }}</cover-view>
            </cover-view>
        </view>
        
        <plate-card :list="plateProdsList"></plate-card>
        
        <u-skeleton :loading="loading"></u-skeleton>
    </view>
</template>

<script>
    import plateCard from './components/area-plate-card';
    import { mapState } from 'pinia';
    import { useUserInfoStore, useIndexStore } from '@/store/index';
    import { saleTypeColor } from '@/common/utils/map-tools';
	import { getAreasForCity, getPolygonForArea, plateProductsForArea } from '@/common/api/houses';
	export default {
        components: {
            plateCard
        },
        data() {
            return {
                areaCode: '',
                tabsLabel: [],
                tabsArr: [],
                current: 0,
                mapContext: null,
                //#ifdef MP-WEIXIN
                longitude: 100.789761,
                latitude: 22.022137,
                //#endif
                //#ifdef MP-BAIDU || MP-TOUTIAO
                longitude: null,
                latitude: null,
                //#endif
                polygons: [],
                loading: true,
                showPlate: false,
                currPlate: 0,
                tags: [
                    { color: "#5FAADD", label: '待销售' },
                    { color: "#0F49BC", label: '认购中' },
                    { color: "#D81C03", label: '在售中' }
                ],
            }
        },
        computed:{
			...mapState(useUserInfoStore, ['userInfo']),
			...mapState(useIndexStore, ['nowCityCode']),

            //区域内所有板块多边形
            platePolygons: function() {
                return this.tabsArr.length === 0 ? [] : this.tabsArr[this.current].polygons;
            },

            markers: function() {
                if(this.tabsArr.length === 0) return [];
                
                const currTabObj = this.tabsArr[this.current];
                let prodMarkerArr = [];
                currTabObj.markers.forEach(parent => {
                    currTabObj.list.forEach(child => {
                        const findPlate = child.title.indexOf(parent.callout.content);
                        if(findPlate !== -1) {
                            parent.callout.bgColor = '#007235';
                        }
                    })
                })
                let platMarkerArr = currTabObj.markers;
                
                if(this.currPlate > 0) {
                    platMarkerArr = [];//隐藏板块marker
                    prodMarkerArr = currTabObj.list[this.currPlate-1].prodMarkers
                }
                
                return [...platMarkerArr, ...prodMarkerArr];
            },

            //板块和楼盘列表
            plateProdsList: function() {
                if(this.tabsArr.length === 0) return [];
                if(this.currPlate > 0) {
                    return [this.tabsArr[this.current].list[this.currPlate-1]]
                }
                return this.tabsArr[this.current].list;
            },
            
            //判断下拉选项列表
            plateSelect: function() {
                return this.tabsArr.length === 0 ? [] : [{title: '全部'}, ...this.tabsArr[this.current].list];
            }
        },
        onShareAppMessage(res) {
            return {
                title: `板块找房`,
                path: `/pages/products/map/plate/page?areaCode=${this.areaCode}&puid=${this.userInfo.id}`,
            }
        },
        //#ifdef MP-WEIXIN
        onShareTimeline() {
            return {
                title: `板块找房`,
                query: `areaCode=${this.areaCode}&puid=${this.userInfo.id}`
            }
        },
        //#endif
        
        onReady() {
            if(this.latitude){
                this.mapContext = uni.createMapContext('plateMap', this);
            }
        },
        onLoad(options){
            const that = this;
            this.areaCode = options.areaCode;
            uni.$check_and_login(function() {
                that.init()
            })
        },

        methods:{
            //重置数据
            reset(){
            	this.products = [];
            	this.next = '';
            	this.loadingType = 'loadmore';
            },

            //初始化
            async init() {
                this.loading = true;
                this.current = -1;

                let areasRes = await getAreasForCity(this.nowCityCode, 'area_share');
                if (areasRes.status === 0) {
                    this.tabsLabel = areasRes.detail;
                    this.tabsArr = areasRes.detail.map(item => ({
                        ...item,
                        polygons: [],
                        markers: [],
                        list: []
                    }));
                    let areaFindIndex = areasRes.detail.findIndex(item => item.value === this.areaCode);
                    this.current = areaFindIndex !== -1 ? areaFindIndex : 0;
                    if(this.tabsLabel[this.current].image){
                      this.shareImage = this.tabsLabel[this.current].image
                    }
                }else {
                    uni.$u.toast(areasRes.detail);
                }

                await this.changeAreaPolygon();

                this.loading = false;
            },

            //切换区域请求相关数据
            async changeAreaPolygon() {
                let currTab = this.tabsArr[this.current];
                this.currPlate = 0;
                if(currTab.polygons.length === 0) {
                    let polygonsRes = await getPolygonForArea(currTab.value);
                    if(polygonsRes.status !== 0) {
                        uni.$u.toast(polygonsRes.detail);
                        return
                    }

                    //区域多边形坐标添加key
                    let polygonsArr = [];
                    for(let i=0; i<polygonsRes.detail.points.length; i++) {
                        polygonsArr.push({
                            longitude: polygonsRes.detail.points[i][0],
                            latitude: polygonsRes.detail.points[i][1]
                        })
                    }

                    //区域内标记点
                    let areaMarkers = [];
                    for(let i=0; i<polygonsRes.detail.children.length; i++) {
                        areaMarkers.push({
                            id: 10000+i,
                            longitude: polygonsRes.detail.children[i].center[0],
                            latitude: polygonsRes.detail.children[i].center[1],
                            width: 2,
                            height: 3,
                            callout: {
                                content: polygonsRes.detail.children[i].title,
                                color: '#FFFFFF',
                                fontSize: 14,
                                bgColor: '#999999',
                                borderRadius: 4,
                                padding: 4,
                                display: 'ALWAYS',
                                anchorY: 3
                            }
                        })
                    }

                    currTab.polygons = [{
                        dashArray: [5, 5],
                        fillColor:'#00723530',
                        strokeColor: '#333333',
                        strokeWidth: 1,
                        points: polygonsArr
                    }];

                    currTab.markers = areaMarkers;
                    polygonsArr = [];
                    areaMarkers = [];
                }

                if(currTab.list.length === 0) {
                    let plateProdRes = await plateProductsForArea(this.tabsArr[this.current].value);
                    if(plateProdRes.status !== 0) {
                        uni.$u.toast(plateProdRes.detail);
                        return
                    }
                    
                    plateProdRes.detail.forEach(item => {
                        let prodMarks = [];
                        item.list.forEach((child, i) => {
                            prodMarks.push({
                                id: 20000 + i,
                                longitude: child.lng,
                                latitude: child.lat,
                                title: child.title,
                                width: 6,
                                heigth: 6,
                                height: 6,
                                alpha: 0,
                                callout: {
                                    content: child.title,
                                    color: '#FFFFFF',
                                    bgColor: saleTypeColor[child.sell_type],
                                    fontSize: 10,
                                    borderRadius: 10,
                                    padding: 4,
                                    display: 'ALWAYS',
                                    textAlign: 'center'
                                }
                            })
                        })
                        item.prodMarkers = prodMarks;
                    })
                    currTab.list = plateProdRes.detail;
                }
                
                this.skewIntoView();
            },

            //多边形展示在地图视口内
            skewIntoView() {
                this.hidePlateSelect();
                
                if(this.mapContext) {
                    //#ifdef MP-BAIDU || MP-TOUTIAO
                    this.mapContext.moveToLocation({
                        longitude: this.longitude,
                        latitude: this.latitude
                    });
                    //#endif
                    let points = this.platePolygons[0].points;
                    if(this.currPlate > 0) {
                        points = this.markers.map(item => ({longitude: item.longitude, latitude: item.latitude}))
                    }
                    this.mapContext.includePoints({
                        points,
                        padding: [20, 30, 20, 30],
                        success: function(e) {}
                    })
                }
            },

            //切换tab
            changeTabs({index}) {
              this.current = index;
              this.areaCode = this.tabsLabel[this.current].value
              if(this.tabsLabel[this.current].image){
                this.shareImage = this.tabsLabel[this.current].image
              }
              
              this.changeAreaPolygon();
            },
            
            //下拉框选择区域
            changePlate(index=0) {
                this.currPlate = index;
                this.skewIntoView();
            },
            
            //点击marker
            clickMarker(e) {
                this.hidePlateSelect();
                
                let findMarker = this.markers.find(item => item.id === e.detail.markerId);
                if(findMarker) {
                    const findPlateI = this.plateSelect.findIndex(item => item.title.indexOf(findMarker.callout.content) !== -1);
                    if(findPlateI !== -1) {
                        this.currPlate = findPlateI;
                        this.skewIntoView();
                        return
                    }
                    
                    let findProd = null;
                    for(let i=0; i<this.plateProdsList.length; i++) {
                        for(let j=0; j<this.plateProdsList[i].list.length; j++) {
                            if(this.plateProdsList[i].list[j].title === findMarker.callout.content) {
                                findProd = this.plateProdsList[i].list[j];
                                break;
                            }
                        }
                    }
                    if(findProd) {
                        uni.navigateTo({
                            url: `/pages/product/detail/index?productId=${findProd.id}&title=${findProd.title}`
                        })
                    }
                }
            },
            
            //地图点击事件
            clickMap() {
                this.hidePlateSelect();
            },
            
            //地图移动触发
            mapMoveChange() {
                this.hidePlateSelect();
            },
            
            //收起下拉框
            hidePlateSelect() {
                this.showPlate = false;
            },
            
            //点击按钮切换下拉框
            changeSelect() {
                this.showPlate = !this.showPlate
            }
        }
    }
</script>

<style scoped lang="scss">
.page{
    min-height: 100vh;
    line-height: 1;
    overflow: hidden;
    .tabsWrap{
        padding-left: 10rpx;
    }
    .mapWrap{
        position: relative;
        .map{
            width: 100%;
            height: 600rpx;
        }
        .topBtnGroup{
            width: calc(100% - 56rpx);
            position: absolute;
            z-index: 1;
            top: 28rpx;
            left: 28rpx;
            justify-content: space-between;
            .openAreaBtn{
                width: 250rpx;
                padding: 12rpx 0;
                border-radius: 6rpx;
                border: 2rpx solid rgba(0,0,0,.1);
                .iconArrow{
                    width: 24rpx;
                    height: 24rpx;
                    border-radius: 50%;
                    padding: 4rpx;
                    .iconImg{
                        width: 100%;
                    }
                }
                .upArrow{
                    transform: rotate(180deg);
                }
            }
            .tag{
                border-radius: 10rpx;
                padding: 4rpx 16rpx 8rpx 16rpx;
            }
        }
        .selecWrap{
            width: 250rpx;
            position: absolute;
            top: 90rpx;
            left: 28rpx;
            z-index: 1;
            border-radius: 6rpx;
            max-height: 400rpx;
            overflow-y: scroll;
            .selectBtn{
                padding: 14rpx 0;
                border-bottom: 2rpx solid rgba(0,0,0,.1);
                &:last-child{
                    border: none;
                }
            }
        }
    }
}
</style>
